import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';

import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import Detail from './Detail';
import AddOrEditPrice from './AddOrEditPrice';
import ReactDataGrid from 'react-data-grid';
const FormItem = Form.Item;
const { confirm } = Modal;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ price, loading,global }) => ({
  price,
  global,
  loading: loading.models.price,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      btnLoading:false
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      price: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        price: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'price/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'price/changeLoaded',
          });
          dispatch({
            type: 'price/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'price/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'price/changeTableY',
    });
  };
  findChildFunc = (cb)=> {
    this.file=cb
  }
  changeTableY = () => {
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'price/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      price: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label="水表号">
          {getFieldDecorator('number', {
            initialValue: searchParams.number,
          })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
        </FormItem>
        <FormItem label="安装地址">
          {getFieldDecorator('address', {
            initialValue: searchParams.address,
          })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    this.setState({
      btnLoading:true
    })
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'price/add',
      payload: {
        ...formValues,
      },
      callback() {
        message.success('添加用水性质成功');
        that.setState({
          addModal: false,
        });
        const {
          price: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
    setTimeout(function() {
      that.setState({
        btnLoading:false
      })
    },1000)
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      number:'',
      user_number:'',
      address:'',
      page: 1,
      per_page: 30,
    });
  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `price/edit`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
        install_date:formValues.install_date?moment(formValues.install_date).format("YYYY-MM-DD"):''
      },
      callback() {
        message.success('修改用水性质成功');
        that.setState({
          editModal: false,
        });
        const {
          price: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `price/remove`,
      payload: { id },
      callback: () => {
        message.success('删除用水性质成功');
        const {
          price: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  renderStatus = (val) => {
    let type = '';
    let color = '';
    let text = '';
    switch (val) {
      case -1:
        type = 'close-circle', color = '#eb2f96', text = '关';
        return <Switch  checkedChildren="开启" unCheckedChildren="关闭" checked={false} />
        break;
      case 1:
        type = 'check-circle', color = '#52c41a', text = '开';
        return <Switch  checkedChildren="开启" unCheckedChildren="关闭" checked={true} />
        break;
      case 2:
        type = 'close-circle', color = '#fe5810', text = '未上报';
        break;
      case 3:
        type = 'close-circle', color = '#fe1b2e', text = '异常';
        break;
      default:
        type = 'close-circle', color = '#eb2f96', text = '异常';
        break;
    }
    return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
  };

  render() {
    const that = this;
    const {
      price: { data, loading, tableY, meta, searchParams, selectedRowKeys, additional },
      global:{gridTableW}
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen:true,
        formatter: (event) => {
          const {
            price: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page-1)*meta.per_page)+(event.value+1)}</p>
        }
      },
      {
        name: '用水性质名称',
        frozen:true,
        width: 210,
        key: 'name',
      },
      {
        name: '打印收据模板',
        key: 'print_receipt_template',
        width: 110,
        formatter:(event)=>{
          return `打印模板${event.value}`
        }
      },
      {
        name: '一阶价格',
        key: 'level_one_price',
        width: 100,
        formatter:(event)=>{
          return <span className={Number(event.value)>0?'green':''}>{event.value}</span>
        }
      },
      {
        name: '一阶污水处理费',
        key: 'level_one_sewage_price',
        width: 120,
        formatter:(event)=>{
          return <span className={Number(event.value)>0?'green':''}>{event.value}</span>
        }
      },
      {
        name: '二阶价格',
        key: 'level_two_price',
        width: 100,
        formatter:(event)=>{
          return <span className={Number(event.value)>0?'green':''}>{event.value}</span>
        }
      },
      {
        name: '二阶污水处理费',
        key: 'level_two_sewage_price',
        width: 120,
        formatter:(event)=>{
          return <span className={Number(event.value)>0?'green':''}>{event.value}</span>
        }
      },
      {
        name: '三阶价格',
        key: 'level_three_price',
        width: 100,
        formatter:(event)=>{
          return <span className={Number(event.value)>0?'green':''}>{event.value}</span>
        }
      },
      {
        name: '三阶污水处理费',
        key: 'level_three_sewage_price',
        width: 120,
        formatter:(event)=>{
          return <span className={Number(event.value)>0?'green':''}>{event.value}</span>
        }
      },
      {
        name: '一阶水量(m3)',
        key: 'level_one_consumption',
        width: 120,
        formatter:(event)=>{
          return <span className={Number(event.value)>0?'green':''}>{event.value}</span>
        }
      },
      {
        name: '二阶水量(m3)',
        key: 'level_two_consumption',
        width: 120,
        formatter:(event)=>{
          return <span className={Number(event.value)>0?'green':''}>{event.value}</span>
        }
      },
      {
        name: '创建时间',
        width: 165,
        key: 'created_at',
      },
      {
        name: '备注',
        width: 150,
        key: 'remark',
      },
      {
        name: '操作',
        width: 80,
        key: 'right',
        classname:'operate',
        formatter: (event) => <Fragment>
          {
            find(this.permissions, { name: "price_nature_adjust" }) &&
              <Fragment>
                <Button
                  type="primary"
                  size="small"
                  icon="edit"
                  onClick={(e) => {
                    this.setState({
                      editRecord: event.row,
                      editModal: true,
                    });
                  }
                  }
                >编辑
                </Button>
              </Fragment>
          }

        </Fragment>,
      },
    ].map(c => ({  ...defaultColumnProperties,...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if(totalWidth<gridTableW){
      columns[columns.length-1].width=   columns[columns.length-1].width+gridTableW-totalWidth
    }
    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>用水性质</span>
      </div>
      <div className="table-page">
        <div className="table-info">
          <div className="table-info-item">
            <p>用水性质总数量(个)</p>
            <h4>{meta.total}</h4>
          </div>
          {
            find(this.permissions, {name: "price_nature_adjust"})&&
            <div size="large" className="table-info-right-item">
              <Button
                icon="plus"
                style={{ marginLeft: 8 }}
                type="primary"
                onClick={
                  () => {
                    this.setState({
                      addModal: true,
                    });
                  }
                }
              >
                添加用水性质
              </Button>
            </div>
          }

        </div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {return {...data[i],_index:i}}}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                if(!String(row)){
                  return
                }
                this.props.dispatch({
                  type: 'price/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading&&<Loading />
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }}
                      resetScrollY={() => {
                        console.log('resetScrollY');
                        const {
                          price: { scrollData },
                        } = this.props;
                        const table = document.querySelector('.react-grid-Canvas');
                        setTimeout(() => {
                          table.scrollTop = 0;
                          table.scrollLeft = scrollData.x;
                        }, 0);

                      }}
                      meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="添加用水性质"/>}
        visible={this.state.addModal}
        centered
        okButtonProps={{loading:this.state.btnLoading}}
        onOk={this.handleAdd}
        className="addModal"
        width={650}
        onCancel={() => {
          this.setState({ addModal: false });
        }}

      >
        <AddOrEditPrice  wrappedComponentRef={(inst) => this.AddForm = inst}  />

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`修改 : ${this.state.editRecord.name}`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        okButtonProps={{loading:this.state.btnLoading}}
        className="editModal"
        width={650}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ editModal: false, editRecord: {} });
        }}

      >
        <AddOrEditPrice
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />

      </Modal>
    </div>;
  }
}

export default BasicList;
